import requests
import os
import socket
import ctypes
from ctypes import wintypes

# 简化的Windows通知功能
def show_notification(title, message, duration=5):
    """显示系统通知，失败时自动使用消息框"""
    try:
        # 基础通知结构
        class NOTIFYICONDATA(ctypes.Structure):
            _fields_ = [
                ("cbSize", wintypes.DWORD),
                ("hWnd", wintypes.HWND),
                ("uID", wintypes.UINT),
                ("uFlags", wintypes.UINT),
                ("szInfo", ctypes.c_wchar * 256),
                ("szInfoTitle", ctypes.c_wchar * 64),
                ("uTimeoutOrVersion", wintypes.UINT),
            ]

        # 加载系统库并配置
        shell32 = ctypes.WinDLL('shell32')
        nid = NOTIFYICONDATA()
        nid.cbSize = ctypes.sizeof(nid)
        nid.uFlags = 0x10  # 仅保留必要标志
        nid.szInfo = message[:255]  # 确保不超过长度限制
        nid.szInfoTitle = title[:63]
        nid.uTimeoutOrVersion = duration * 1000

        # 尝试显示通知
        if not shell32.Shell_NotifyIconW(0, ctypes.byref(nid)):
            raise Exception("通知显示失败")
            
    except:
        # 任何错误都使用消息框作为备用
        ctypes.windll.user32.MessageBoxW(0, message, title, 0x40)

def get_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(('8.8.8.8', 80))
    ip = s.getsockname()[0]
    s.close()
    return ip

def logout(logout_url):
    """执行注销操作"""
    try:
        response = requests.get(logout_url, timeout=5)
        return "注销成功" in response.text or response.status_code == 200
    except Exception as e:
        print(f"注销时发生错误: {e}")
        return False

if __name__ == '__main__':
    # 配置变量（请根据实际情况修改）
    login_IP = 'http://172.29.0.2'    
    not_sign_in_title = '上网登录页'
    result_return = '协议认证成功'
    sign_parameter = f'' # 登陆成功时的请求 URL
    signed_in_title = '注销页'
    logout_parameter = f''# 注销成功时的请求 URL

    try:
        r = requests.get(login_IP, timeout=1)
        req = r.text
    except:
        req = 'False'

    if signed_in_title in req:
        logout_success = logout(logout_parameter)
        show_notification(
            "注销结果", 
            "已成功退出校园网" if logout_success else "注销失败，请重试"
        )

    elif not_sign_in_title in req:
        r = requests.get(sign_parameter, timeout=1)
        req = r.text
        show_notification(
            "登录结果", 
            "已成功连接校园网" if result_return in req else "登录失败，请重试"
        )

    else:
        show_notification("网络状态", "未连接到校园网，请检查")

    os._exit(0)
    
